<template>
  <div class="inspection-container">
    <el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
      <el-col :span="24" class="text-center">
        <div class="title-wrapper">
          <i class="el-icon-search el-icon--large"></i>
          <h1 class="main-title">道路环境检查记录管理系统</h1>
          <p class="sub-title">全面记录道路环境检查信息，及时处理各类道路环境问题，保障道路安全畅通</p>
        </div>
      </el-col>
    </el-row>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="检查记录详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="检查记录信息" direction="vertical" :column="4" :model="currentInspection" border>
        <el-descriptions-item label="记录ID" :span="2">{{ currentInspection.id }}</el-descriptions-item>
        <el-descriptions-item label="位置ID" :span="2">{{ currentInspection.pointId }}</el-descriptions-item>
        <el-descriptions-item label="检查类型" :span="2">{{ currentInspection.inspectionType }}</el-descriptions-item>
        <el-descriptions-item label="处理状态" :span="2">{{ currentInspection.status }}</el-descriptions-item>
        <el-descriptions-item label="车辆ID" :span="4">{{ currentInspection.carId }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑检查记录"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="记录ID" prop="id" disabled>
          <el-input v-model="editForm.id"></el-input>
        </el-form-item>
        <el-form-item label="位置ID" prop="pointId">
          <el-input v-model.number="editForm.pointId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="检查类型" prop="inspectionType">
          <el-select v-model="editForm.inspectionType" placeholder="请选择检查类型">
            <el-option label="汽车占道" value="汽车占道"></el-option>
            <el-option label="路面损坏" value="路面损坏"></el-option>
            <el-option label="环境卫生" value="环境卫生"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择处理状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆ID" prop="carId">
          <el-input v-model.number="editForm.carId" type="number"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增检查记录"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="位置ID" prop="pointId">
          <el-input v-model.number="addForm.pointId" type="number" placeholder="请输入位置ID"></el-input>
        </el-form-item>
        <el-form-item label="检查类型" prop="inspectionType">
          <el-select v-model="addForm.inspectionType" placeholder="请选择检查类型">
            <el-option label="汽车占道" value="汽车占道"></el-option>
            <el-option label="路面损坏" value="路面损坏"></el-option>
            <el-option label="环境卫生" value="环境卫生"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择处理状态">
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆ID" prop="carId">
          <el-input v-model.number="addForm.carId" type="number" placeholder="请输入车辆ID"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区和表格部分 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input 
            placeholder="输入位置ID进行查询" 
            v-model="searchPointId" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="searchStatus" 
            placeholder="按处理状态筛选" 
            style="width: 100%;"
          >
            <el-option label="全部状态" value=""></el-option>
            <el-option label="待处理" value="待处理"></el-option>
            <el-option label="处理中" value="处理中"></el-option>
            <el-option label="已处理" value="已处理"></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="searchInspectionType" 
            placeholder="按检查类型筛选" 
            style="width: 100%;"
          >
            <el-option label="全部类型" value=""></el-option>
            <el-option label="汽车占道" value="汽车占道"></el-option>
            <el-option label="路面损坏" value="路面损坏"></el-option>
            <el-option label="环境卫生" value="环境卫生"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="info" 
            @click="fetchAllOccupancy" 
            style="width: 100%;"
          >
            <i class="el-icon-truck"></i> 汽车占道
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="id" label="记录ID" width="120" align="center"></el-table-column>
        <el-table-column prop="pointId" label="位置ID" width="100" align="center"></el-table-column>
        <el-table-column prop="inspectionType" label="检查类型" width="140" align="center">
          <template #default="scope">
            <el-tag :type="getInspectionTypeTag(scope.row.inspectionType)">
              {{ scope.row.inspectionType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="carId" label="车辆ID" width="100" align="center"></el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" @click="openDetailDialog(scope.row)">
                <i class="el-icon-view"></i> 查看
              </el-button>
              <el-button type="warning" size="mini" @click="openEditDialog(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="danger" size="mini" @click="deleteInspection(scope.row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'


// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)


// 搜索条件
const searchPointId = ref('')
const searchStatus = ref('')
const searchInspectionType = ref('')


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)


// 数据存储
const inspectionList = ref([])
const filteredData = ref([])


// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)


// 当前选中的检查记录信息
const currentInspection = reactive({
  id: null,
  pointId: null,
  inspectionType: '',
  status: '',
  carId: null
})


// 编辑表单数据
const editForm = reactive({
  id: null,
  pointId: null,
  inspectionType: '',
  status: '',
  carId: null
})


// 新增表单数据
const addForm = reactive({
  pointId: null,
  inspectionType: '',
  status: '',
  carId: null
})


// 表单验证规则
const rules = reactive({
  pointId: [
    { required: true, message: '请输入位置ID', trigger: 'blur' },
    { type: 'number', message: '位置ID必须为数字', trigger: 'blur' }
  ],
  inspectionType: [
    { required: true, message: '请选择检查类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择处理状态', trigger: 'change' }
  ],
  carId: [
    { required: true, message: '请输入车辆ID', trigger: 'blur' },
    { type: 'number', message: '车辆ID必须为数字', trigger: 'blur' }
  ]
})


// 根据检查类型获取标签样式
const getInspectionTypeTag = (type) => {
  switch(type) {
    case '汽车占道': return 'warning'
    case '路面损坏': return 'danger'
    case '环境卫生': return 'success'
    case '其他': return 'info'
    default: return ''
  }
}


// 根据处理状态获取标签样式
const getStatusTag = (status) => {
  switch(status) {
    case '待处理': return 'info'
    case '处理中': return 'warning'
    case '已处理': return 'success'
    default: return ''
  }
}


// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  Object.assign(currentInspection, row)
}


// 打开编辑对话框
function openEditDialog(row) {
  editDialogVisible.value = true
  Object.assign(editForm, {
    id: row.id,
    pointId: row.pointId,
    inspectionType: row.inspectionType,
    status: row.status,
    carId: row.carId
  })
}


// 打开新增对话框
function openAddDialog() {
  addDialogVisible.value = true
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  addForm.pointId = null
  addForm.inspectionType = ''
  addForm.status = ''
  addForm.carId = null
}


// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '更新中...' })
    // 构建URL参数
    const params = new URLSearchParams()
    params.append('id', editForm.id)
    params.append('pointId', editForm.pointId)
    params.append('inspectionType', editForm.inspectionType)
    params.append('status', editForm.status)
    params.append('carId', editForm.carId)
    
    post(`/sc/roadenv/updateById?${params.toString()}`, {}, (res) => {
      loading.close()
      if (res.status || res.msg?.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchInspectionList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}


// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/roadenv/add', addForm, (res) => {
      loading.close()
      if (res.status || res.msg?.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchInspectionList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}


// 删除检查记录
function deleteInspection(row) {
  ElMessageBox.confirm(`确定删除检查记录 ${row.id} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/roadenv/deleteById', { id: row.id }, (res) => {
      loading.close()
      if (res.status || res.msg?.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchInspectionList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}


// 搜索处理
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  // 按状态搜索
  if (searchStatus.value) {
    post('/sc/roadenv/byStatus', { status: searchStatus.value }, (res) => {
      loading.close()
      handleSearchResult(res)
    })
  } 
  // 按检查类型本地过滤
  else if (searchInspectionType.value) {
    filteredData.value = inspectionList.value.filter(item => 
      item.inspectionType === searchInspectionType.value
    )
    loading.close()
    showSearchResultMessage()
  }
  // 按位置ID本地过滤
  else if (searchPointId.value) {
    filteredData.value = inspectionList.value.filter(item => 
      item.pointId.toString().includes(searchPointId.value)
    )
    loading.close()
    showSearchResultMessage()
  }
  // 显示全部
  else {
    filteredData.value = [...inspectionList.value]
    loading.close()
    showSearchResultMessage()
  }
  
  currentPage.value = 1 // 重置到第一页
}


// 专门查询汽车占道记录
function fetchAllOccupancy() {
  const loading = ElLoading.service({ text: '加载汽车占道记录中...' })
  post('/sc/roadenv/getAllOccupancy', {}, (res) => {
    loading.close()
    handleSearchResult(res)
    searchInspectionType.value = '汽车占道'
  })
}


// 处理搜索结果
function handleSearchResult(res) {
  if (res && res.data) {
    filteredData.value = res.data
  } else if (Array.isArray(res)) {
    filteredData.value = res
  } else {
    filteredData.value = []
  }
  showSearchResultMessage()
}


// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}


// 重置搜索
function resetSearch() {
  searchPointId.value = ''
  searchStatus.value = ''
  searchInspectionType.value = ''
  filteredData.value = [...inspectionList.value]
  currentPage.value = 1
}


// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}


// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}


// 获取所有检查记录
function fetchInspectionList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/roadenv/getAll', {}, (res) => {
    loading.close()
    if (res.status) {
      inspectionList.value = res.data
      filteredData.value = [...res.data]
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      inspectionList.value = []
      filteredData.value = []
    }
  })
}


// 页面加载时获取数据
onMounted(() => {
  fetchInspectionList()
})
</script>


<style scoped>
.inspection-container {
  width: auto;
  padding: 20px;
}

/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}

.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
}

.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}

.el-form {
  padding: 10px;
}
</style>
